package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartProductConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * create by heyyon 2020-12-20 20:30
 * 添加商品到购物车
 */
@Service
@Component
@Slf4j
public class   AddCartServiceImpl implements ICartService {
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    CartProductConverter converter;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        List<CartProductDto> cartProductDtos = new ArrayList<>();

        try {
            String userIdStr = String.valueOf(request.getUserId());
            RMap<Object, Object> rMap = redissonClient.getMap(userIdStr);
            System.out.println("before list "+rMap.readAllEntrySet());
            Set<Map.Entry<Object, Object>> entries = rMap.readAllEntrySet();
            for (Map.Entry<Object, Object> entry : entries) {
                CartProductDto cartProduct = (CartProductDto) entry.getValue();
                cartProductDtos.add(cartProduct);
            }
            response.setCartProductDtos(cartProductDtos);
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            log.info("IProductServiceImpl.getCartListById occur Exception:{}", e);
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;

    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        Item item = itemMapper.selectByPrimaryKey(request.getItemId());
        String imgStr=item.getImage();
        if (imgStr.contains(",")) {
            item.setImage(imgStr.substring(0,imgStr.indexOf(",")));
        }
        CartProductDto cartProductDto = converter.item2CartProductDto(item);
        cartProductDto.setChecked("true");
        cartProductDto.setProductNum(request.getNum());
        AddCartResponse addCartResponse = new AddCartResponse();
        try {
            String userIdStr = String.valueOf(request.getUserId());
            String productStr = String.valueOf(request.getItemId());
            RMap<Object, Object> rMap = redissonClient.getMap(userIdStr);
//            System.out.println("before add "+rMap.readAllEntrySet());
            boolean exist = rMap.containsKey(productStr);
            //判断是否已经存在该key，不存在则直接添加
            if (!exist) {
                rMap.put(productStr, cartProductDto);
            } else {
                //若存在，则加对应的数量
                Long productNum = ((CartProductDto) rMap.get(productStr)).getProductNum();
                productNum += request.getNum();
                cartProductDto.setProductNum(productNum);
                rMap.put(productStr, cartProductDto);
            }
            //测试用  打印
//            System.out.println("after add "+rMap.readAllEntrySet());
//            System.out.println((CartProductDto)rMap.get("100040607"));
//            System.out.println(((CartProductDto)rMap.get("100040607")).getProductNum());
            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("AddCartServiceImpl.addToCart Occur Exception:" + e);
            ExceptionProcessorUtils.wrapperHandlerException(addCartResponse, e);
        }
        return addCartResponse;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        return null;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        return null;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {

        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            String userIdStr = String.valueOf(request.getUserId());
            String productStr = String.valueOf(request.getItemId());
            RMap<Object, Object> rMap = redissonClient.getMap(userIdStr);
            //System.out.println("before del "+rMap.readAllEntrySet());
            rMap.fastRemove(productStr);
            //System.out.println("after del "+rMap.readAllEntrySet());
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            log.info("IProductServiceImpl.deleteCartItem occur Exception:{}", e);
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }


    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            String userIdStr = String.valueOf(request.getUserId());
            RMap<Object, Object> rMap = redissonClient.getMap(userIdStr);
            Set<Map.Entry<Object, Object>> entries = rMap.readAllEntrySet();
            for (Map.Entry<Object, Object> entry : entries) {
                CartProductDto cartProduct = (CartProductDto) entry.getValue();
                if ("true".equals(cartProduct.getChecked())) {
                    rMap.remove(cartProduct.getProductId().toString());
                }
            }
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            log.info("IProductServiceImpl.deleteCheckedItem occur Exception:{}", e);
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
